package com.atguigu.gmall.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author:lyd
 **/
@Slf4j
public class JsonUtil {

    //Spring框架中自带的Jackson转换json工具
   private static ObjectMapper objectMapper = new ObjectMapper();

   public static String objToJsonStr(Object obj){
       String str = null;
       try {
           str = objectMapper.writeValueAsString(obj);
       } catch (JsonProcessingException e) {
           log.error("json转换异常");
       }
       return str;
   }

    /**
     * json字符串转为Java对象
     * @param str
     * @param objectClass
     * @return
     * @param <T>
     */
    public static <T> T strToObj(String str, Class<T> objectClass) {
        T t = null;
        try {
             t = objectMapper.readValue(str, objectClass);
        } catch (JsonProcessingException e) {
            log.error("json转java对象异常");
        }
        return t;
    }

    /**
     * json字符串转为复杂的Java对象
     * 比如  List<User> 原对象是泛型套泛型
     * @param str
     * @param valueTypeRef
     * @return
     * @param <T>
     */
    public static <T> T strToObj(String str, TypeReference<T> valueTypeRef) {
        T t = null;
        try {
            t = objectMapper.readValue(str, valueTypeRef);
        } catch (JsonProcessingException e) {
            log.error("json转java对象异常");
        }
        return t;
    }
}
